<?php

/**
 * 合同流水号仓库
 * @author wangwx 2015-5-19
 */

namespace common\repositories\myhtsq;

use common\repositories\BaseRepository;
use common\entities\myhtsq\ContractFlowCodeEntity;
use common\entities\myhtsq\ContractManageEntity;
use common\entities\ConfigEntity;

class ContractFlowCodeRepository extends BaseRepository
{

    /**
     * 构造函数
     * @param type $config
     */
    public function __construct($config = [])
    {
        parent::__construct($config);
    }

    /**
     * 获取最大合同编号流水号
     * @return int 最大合同编号流水号
     */
    public static function getMaxContractFlowCode()
    {
        return ContractFlowCodeEntity::find()->max('code_id');
    }

    /**
     * 新增合同流水号
     * @param string $contractId 合同id
     * @return boolean|string
     */
    public static function addContractFlowCode($contractId)
    {
        $contractFlowCode = new ContractFlowCodeEntity();
        $contractFlowCode->contract_id = $contractId;
        if ($contractFlowCode->save()) {
            return $contractFlowCode->primaryKey;
        } else {
            return false;
        }
    }


    /**
     * 组合生成合同编号
     * 组合规则：区域（SH）-客户简称（客户拼音字母简称，从商机系统获取）- FW20150102流水（0001）
     * @param string $areaCode 区域id
     * @param string $customerId 客户id
     * @param string $flowCode 流水号
     * @param string $contractCode 合同编号
     * @return string
     */
    public static function createContractCode($areaCode, $customerId, $flowCode, $contractCode)
    {
//        if ($flowCode <= 0) {
//            $flowCode = 1;
//        }
//
//        if (empty($contractCode)) {//新增获取
//            $timestamp = ConfigEntity::getDbNowTimestamp();//取数据库时间截
//            $date = date("ymdHis", $timestamp);
//            $str = '';
//            if (!empty($areaCode)) {
//                $str .= $areaCode . '-';
//            }
//            if (!empty($customerId)) {
//                $str .= $customerId . '-';
//            }
//            return strtoupper($str . 'YFW' . $date . sprintf("%04d", $flowCode));
//        } else {//更改 获取编号
//            $split_code = 'YFW';
//            if (!strpos($contractCode, '-YFW')) {
//                $split_code = 'FW';
//            }
//            $arr = explode("-" . $split_code, $contractCode);
//            $str = '';
//            if (!empty($areaCode)) {
//                $str .= $areaCode . '-';
//            }
//            if (!empty($customerId)) {
//                $str .= $customerId . '-';
//            }
//            return strtoupper($str . $split_code . $arr[1]);
//        }

        return self::getContractCode();
    }

    /**
     * 获取合同编码,确保不重复使用Code
     * @return string
     */
    public static function getContractCode(){
        $code = self::makeContractCode();
        $contract = ContractManageEntity::find()->where(['contract_code'=>$code])->one();
        while(!empty($contract)){
            $code = self::makeContractCode();
            $contract = ContractManageEntity::find()->where(['contract_code'=>$code])->one();
        }
        return $code;
    }

    /**
     * 产生合同Code
     * @return string
     */
    private static function makeContractCode(){
        $timestamp = ConfigEntity::getDbNowTimestamp();
        $datetime = date("Ymd", $timestamp);
        $contractCode = 'YL-'.$datetime.'-';
        $random = (string)rand(100000,999999);
        $contractCode = $contractCode.$random;
        return $contractCode;
    }
}
